package dianmobile.eistarandroid.ui.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.network.request.PostRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.network.request.RequestType;
import dianmobile.eistarandroid.ui.views.SwipeActivity;
import dianmobile.eistarandroid.utils.ConstantsData;

public class PostArticleActivity extends SwipeActivity {

    private String sendTo;
    private String fileName;    //回复的文件名
    private String postType;
    private TextView tvActivityTitle;
    private TextView tvSendTo;
    private EditText edtArticleTitle;
    private EditText edtArticleDetail;
    private CheckBox unReply;
    private CheckBox anonymity;
    private ImageButton btnInsertImage;
    private ImageButton btnInsertemotion;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ByhhAndroidApplication application = (ByhhAndroidApplication) getApplication();
        application.getActivityList().add(this);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_post_article);

        Intent intent = getIntent();

        initView(intent);

    }

    @Override
    public void onDestroy() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int key, KeyEvent event) {
        if (key == KeyEvent.KEYCODE_BACK){
            onBackClick();
            return true;
        } else {
            return super.onKeyDown(key, event);
        }
    }
    /**
     * 按下返回键的处理
     */
    private void onBackClick(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PostArticleActivity.this);
        builder.setMessage("是否取消发布？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                PostArticleActivity.this.setResult(RESULT_CANCELED);
                PostArticleActivity.this.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void initView(Intent intent) {

        ImageButton btnBack = (ImageButton) findViewById(R.id.btn_back);
        tvActivityTitle = (TextView)findViewById(R.id.tv_activity_title);
        ImageButton btnSend = (ImageButton) findViewById(R.id.btn_send);
        tvSendTo = (TextView)findViewById(R.id.tv_send_to);
        edtArticleTitle = (EditText)findViewById(R.id.edt_article_title);
        edtArticleDetail = (EditText)findViewById(R.id.edt_article_detail);
        unReply = (CheckBox)findViewById(R.id.checkbox_unReply);
        anonymity = (CheckBox)findViewById(R.id.checkbox_anonymity);
        btnInsertemotion = (ImageButton)findViewById(R.id.btn_insert_emotion);
        btnInsertImage = (ImageButton)findViewById(R.id.btn_insert_images);

        postType = intent.getStringExtra(ConstantsData.EXTRA_POST_TYPE);
        tvActivityTitle.setText(postType);
        if (postType.equals(ConstantsData.POST_TYPE_NEW)) {
            sendTo = intent.getStringExtra(ConstantsData.EXTRA_BOARD_NAME);
            if (sendTo.equals("Sex") || sendTo.equals("Anonymous")){    //可匿名版块
                anonymity.setChecked(true);
            } else {
                anonymity.setVisibility(View.INVISIBLE);
            }

        } else if (postType.equals(ConstantsData.POST_TYPE_REPLY)) {
            sendTo = intent.getStringExtra(ConstantsData.EXTRA_BOARD_NAME);
            if (sendTo.equals("Sex") || sendTo.equals("Anonymous")){    //可匿名版块
                anonymity.setChecked(true);
            } else {
                anonymity.setVisibility(View.INVISIBLE);
            }
            fileName = intent.getStringExtra(ConstantsData.EXTRA_FILE_NAME);

            edtArticleTitle.setText(getReplyFileName(intent.getStringExtra(ConstantsData.REPLY_TITLE)));
            edtArticleTitle.setAlpha((float)0.54);
            edtArticleTitle.setEnabled(false);
            edtArticleDetail.setText("\n"+intent.getStringExtra(ConstantsData.REPLY_SUMMARY));
            edtArticleDetail.requestFocus();
            edtArticleDetail.setSelection(0);
        } else if(postType.equals(ConstantsData.POST_TYPE_MAIL)) {
            unReply.setVisibility(View.INVISIBLE);
            anonymity.setVisibility(View.INVISIBLE);
            btnInsertImage.setVisibility(View.INVISIBLE);
            sendTo = intent.getStringExtra(ConstantsData.EXTRA_USER_NAME);
        }
        tvSendTo.setText(sendTo);

        TitleClickListener titleClickListener = new TitleClickListener();
        btnBack.setOnClickListener(titleClickListener);
        btnSend.setOnClickListener(titleClickListener);
    }


    private void sendRequest() {

        Map<String, String> params = new HashMap<>();
        makeParams(params, postType);
        RequestType requestType = RequestType.POST_NEW_ARTICLE;
        if(postType.equals(ConstantsData.POST_TYPE_MAIL)) {
            requestType = RequestType.POST_MAIL;
        }
        PostRequest.execute(this, requestType, params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                //TODO 有的错误没有判断出来
                if (error != null) {
                    Toast.makeText(PostArticleActivity.this, "网络异常！发送失败！", Toast.LENGTH_SHORT).show();
                } else {
                    if (result.containsKey(ConstantsData.ERROR_RESULT)) {
                        Toast.makeText(PostArticleActivity.this, result.get(ConstantsData.ERROR_RESULT) + "发送失败！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(PostArticleActivity.this, "发送成功！", Toast.LENGTH_SHORT).show();
                        PostArticleActivity.this.setResult(RESULT_OK);
                        PostArticleActivity.this.finish();
                    }
                }
            }
        });
    }

    private void makeParams(Map<String, String> params, String postType) {
        //Map<String, String> params = new HashMap<>();
        switch (postType) {
            case ConstantsData.POST_TYPE_NEW:
                params.put("board", sendTo);
                params.put("userid", ByhhAndroidApplication.acquire(this).getLoginManager().getSavedAccount());
                params.put("title", edtArticleTitle.getText().toString());
                params.put("text", edtArticleDetail.getText().toString());
                if (unReply.isChecked()) {
                    params.put("nore", "on");
                } else {
                    params.put("nore", "off");
                }
                if (anonymity.isChecked()) {
                    params.put("ano", "on");
                }
                params.put("signature", "1");
                params.put("xml", "1");
                break;
            case ConstantsData.POST_TYPE_REPLY:
                params.put("board", sendTo);
                params.put("title", edtArticleTitle.getText().toString());
                params.put("text", edtArticleDetail.getText().toString());
                if (unReply.isChecked()) {
                    params.put("nore", "on");
                } else {
                    params.put("nore", "off");
                }
                if (anonymity.isChecked()) {
                    params.put("ano", "1");
                }
                params.put("signature", "1");
                params.put("file", fileName);
                params.put("xml", "1");
                break;
            case ConstantsData.POST_TYPE_MAIL:
                params.put("userid", sendTo);
                params.put("title", edtArticleTitle.getText().toString());
                params.put("text", edtArticleDetail.getText().toString());
                params.put("nore", "off");
                params.put("xml", "1");
                params.put("backup", "on");     //保存到发件箱
                break;
            default:
                break;
        }
        //return params;
    }
    class TitleClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    onBackClick();
                    break;
                case R.id.btn_send:
                    PostArticleActivity.this.sendRequest();
                    break;
                default:
                    break;
            }
        }
    }
    /** @param rawName 是文件原始的名字前后加了空格**/
    private String getReplyFileName(String rawName){
        StringBuffer sb = new StringBuffer(rawName);
        sb.deleteCharAt(sb.length() - 1);
        return "Re:" + sb.toString();
    }
}
